var ui = new Object();

ui.dialog = {
    createFolder: function(event) {
        $("#dialog .dialog-section").hide();
        $("#create-folder").show();
        dialog.show();
        $("#create-folder #new-folder").val("");
        $("#create-folder #new-folder").focus();
    }
}

ui.items = {
    isInStock: function(target) {
        var isInStock = false;
        var searchString = $(target).text();
        $("#browser-stock").find(".fn, .dn").each(function() {
            if ($(this).text() == searchString && lastAccessedLocation == $(target).attr("base")) {
                isInStock = true;
            }
        });
        
        // console.log("Search: " + searchString + " > " + isInStock);
        
        return isInStock;
    },
    clearStock: function(event) {
        $("#browser-forest .entry.e-selected").each(function () {
            $(this).removeClass("e-selected");
            ui.items.swapIconToOriginalState(this);
        });
        $("#browser-stock .entry").remove();
        getNumberOfSelectedItems();
    },
    clickItem: function(event) {
        ui.items.select(this);
        ui.items.renderInfoPane(event, this);
    },
    synchronizeSelection: function() {
        //console.log("Syncing...");
        if ($("#browser-stock .entry").length > 0) {
            $("#browser-forest").find(".fn, .dn").each(function() {
                var self = $(this).parent().parent();
                if (ui.items.isInStock(this)) {
                    self.addClass("e-selected");
                    ui.items.swapIcon(self);
                } else {
                    self.removeClass("e-selected");
                    ui.items.swapIconToOriginalState(self);
                }
            });
        } else {
            $("#browser-forest .entry").removeClass("e-selected");
            ui.items.swapIconToOriginalState($("#browser-forest .entry"));
        }
    },
    removeItemFromStock: function(target) {
        var searchString = target.text();
        $("#browser-stock")
          .find(".file .fn:contains(" + searchString + "), .directory .dn:contains(" + searchString + ")")
          .each(function() {
            var self = $(this);
            if (self.text() == target.text() && lastAccessedLocation == target.attr("base")) {
                $(this).parent().parent().remove();
            }
        });
    },
    removeItemInStock: function() {
        $(this).parent().parent().parent().remove();
        ui.items.synchronizeSelection();
        getNumberOfSelectedItems();
    },
    showInfo: function(event) {
        if ($("#browser").hasClass("display-stock")) {
            return;
        }
        ui.items.renderInfoPane(event, this);
        ui.items.swapIcon(this);
        return;
    },
    swapIcon: function(self) {
        $(self).each(function() {
            var selfImg = $(this).find(".icon");
            var src = selfImg.attr("src");
            if ($(this).hasClass("e-selected") && src.match(/focus\.\w+$/)) {
                return;
            }
            if (!$(this).hasClass("e-selected") && src.match(/focus\.\w+$/)) {
                return;
            }
            if (src.match(/([\-a-zA-Z0-9]+)\.(\w+)$/)) {
                selfImg.attr("src", src.replace(/([\-a-zA-Z0-9]+)\.(\w+)$/, RegExp.$1 + "-focus." + RegExp.$2));
            }
        });
    },
    swapIconToOriginalState: function(selector) {
        $(selector).each(function() {
            var selfImg = $(this).find(".icon");
            var src = selfImg.attr("src");
            if ($(this).hasClass("e-selected")) return;
            if (src.match(/([\-\w0-9]+)-focus\.(\w+)$/)) {
                selfImg.attr("src", src.replace(/([\-\w0-9]+)-focus\.(\w+)$/, RegExp.$1 + "." + RegExp.$2));
            }
        });
    },
    hideInfo: function(event) {
        ui.items.destroyInfoPane(event);
        ui.items.swapIconToOriginalState(this);
    },
    select: function(selector) {
        $(selector).each(function(index) {
            $(this).toggleClass("e-selected");
            ui.items.swapIcon(this);
            
            // Append or remove from the stock
            if ($(this).hasClass("e-selected")) {
                if (ui.items.isInStock($(this).find(".fn,.dn"))) {
                    return;
                }
                $(this).clone().appendTo("#browser-stock-list");
                $("#browser-stock .entry:last").find(".fn, .dn").attr("base", lastAccessedLocation);
            } else {
                var target = $(this).find(".fn, .dn");
                ui.items.removeItemFromStock(target);
            }
        });
        
        getNumberOfSelectedItems();
    },
    selectAll: function(event) {
        if ($("#browser-forest .entry.e-marked").length == 0) {
            ui.items.select("#browser-forest .entry:not(.e-selected)");
        } else {
            ui.items.select("#browser-forest .entry.e-marked:not(.e-selected)");
        }
    },
    selectNone: function(event) {
        ui.items.select("#browser-forest .e-selected");
        ui.items.swapIconToOriginalState("#browser-forest .entry");
    },
    filter: function(event) {
        var input = $.trim($(this).val());
        if (input == "") {
            $("#browser-filter a").hide();
            $(this).removeClass("e-marked");
            $(".entry").fadeTo(200, 1.0);
        } else {
            var searchInput = new RegExp(input);
            $(".entry").each(function(index) {
                if ($(this).find(".fn, .dn").text().match(searchInput)) {
                    $(this).addClass("e-marked");
                    $(this).fadeTo(200, 1.0);
                } else {
                    $(this).removeClass("e-marked");
                    $(this).fadeTo(200, 0.2);
                }
            });
            $("#browser-filter a").show();
        }
    },
    filterCancel: function(event) {
        $(".e-marked").removeClass("e-marked");
        $(this).parent().find("input").val("");
        $(this).parent().find("input").change();
    },
    renderInfoPane: function(event, elem) {
        if ($("#browser").hasClass("view-tn")) {
            // in thumbnail mode
            return;
        }
        
        var self = this;
        
        if (elem) {
            self = elem;
        }
        
        var mx = event.pageX;
        var my = event.pageY;
        
        if ($("#sstt").length == 0) {
            $("body").append(
                '<div id="sstt"'
                + ' style="">'
                + '<div id="sstt-content" style="max-width:300px; padding: 10px;"></div></div>');
        }
        
        var message = '<h3 style="overflow:hidden; padding: 0; margin: 0; font-size: 16px; font-weight: normal; text-align: center; letter-spacing: 2px;">' + $(self).find(".dn, .fn").text() + '</h3>'
        if ($(self).find(".ft").text() != "" || $(self).hasClass("e-selected")) {
            message += '<p style="padding: 0; margin: 0; border-top: 1px solid #333; text-align: center; font-size: 9px; text-transform: uppercase; color: #999;">';
            if ($(self).hasClass("e-selected")) {
                message += 'Selected'
            } else {
                message += $(self).find(".ft").text()
                    + ' (' + $(self).find(".fs").text() + ')';
            }
            message += '</p>';
        }
        
        $("#sstt-content").html(message);
        
        $("#sstt").fadeIn(500);
        
        ui.items.repositionInfoPane(event, this);
    },
    repositionInfoPane: function(event, elem) {
        if ($("#sstt").length == 0) {
            return;
        }
        
        var self = this;
        
        if (elem) {
            self = elem;
        }
        
        var rx = "left";
        var ry = "top";
        var cx = parseInt($("#sstt").width());
        var cy = parseInt($("#sstt").height());
        var wx = parseInt($(window).width());
        var wy = parseInt($(window).height());
        var mx = event.pageX;
        var my = event.pageY;
        var ax = 20;
        var ay = 20;
        var gx = 45;
        var gy = 45;
        
        if (cx + mx + gx > wx) {
            mx -= cx;
            ax *= -1;
        }
        
        if (cy + my + gy > wy) {
            my -= cy;
            ay *= -1;
        }
        
        //console.log("Position: " + (cx + mx) + "/" + wx + ", " + (cy + my) + "/" + wy);
        
        $("#sstt").css(rx, mx + ax);
        $("#sstt").css(ry, my + ay);
    },
    destroyInfoPane: function(event) {
        if ($("#sstt").length > 0) {
            $("#sstt").remove();
        }
    }
}

ui.state = {
    afterSuccessfulBatchOperation: function(event) {
        $("#browser-stock .entry").remove();
        browse();
        dialog.hide();
    },
    afterFailedBatchOperation: function(event) {
        dialog.show(dictionary.locale.message.error.failedToComplyRequest, false, true);
    },
    userAuthorizationDenied: function() {
        // Remove the highlight
        $("#controller a").removeClass("e-selected");
        
        // Hide all non-secure items
        $(".sl-nauth").show();
        
        // Show all secure items
        $(".sl-auth").hide();
        
        // Show the browser
        $("#display > div").hide();
        
        // Hide the user I/O
        $("#user-io").show();
        
        // Show the welcome message
        $("#user-id").html(dictionary.locale.message.event.welcome());
        
        // Force to sign-in
        $("#a-signin").click();
    },
    userAuthorizationGranted: function() {
        // Remove the highlight
        $("#controller li").removeClass("e-selected");
        
        // Hide all non-secure items
        $(".sl-nauth").hide();
        
        // Show all secure items
        $(".sl-auth").show();
        
        // Hide the user I/O
        $("#user-io").hide();
        
        // Show the browser
        $("#browser").show();
        
        // Show the user ID (user name)
        $("#user-id").html(dictionary.locale.message.event.welcome(userID));
        
        // Select "Browse"
        $("#a-browse").click();
        
        // Change the destination for the user profile
        $("#a-user-info").attr("href", appBase + "/users/" + userID);
    }
}